using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Web;
using OpenWaves.ActivityFeed.Web.Modules;

namespace OpenWaves.ActivityFeed.Web.Handler
{
    public class HttpHandler : RestModule, IHttpHandler
    {
        [SuppressMessage("Microsoft.Naming", "CA1713:EventsShouldNotHaveBeforeOrAfterPrefix")]
        protected event EventHandler<HttpHandlerPipelineEventArgs> Before = delegate { };

        public HttpHandler(params IRestModule[] modules)
        {
            foreach (var action in modules.SelectMany(module => module.Actions))
            {
                this.Actions.Add(action.Key, action.Value);
            }
        }

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            this.ProcessRequest(new HttpContextWrapper(context));
        }

        public void ProcessRequest(HttpContextBase context)
        {
            foreach (var actionDefinition in this.Actions)
            {
                IDictionary<string, string> parameters;
                if (actionDefinition.Key.Match(context.Request.HttpMethod, Url.FromUri(context.Request.Url), out parameters))
                {
                    var pipelineEventArgs = new HttpHandlerPipelineEventArgs(context);
                    this.Before(this, pipelineEventArgs);
                    if (pipelineEventArgs.IsRequestHandled)
                        return;

                    var result = actionDefinition.Value(context.Request, parameters);
                    result.Execute(context.Response);
                    return;
                }
            }

            context.Response.StatusCode = 404;
        }
    }
}